let lock = require('async-lock');
let log = require("./loginfo").getInstand;

let taskList = [];
let cnt = 0;
let runInternalTime = null;
let lk = new lock();

exports.StartInterval = function StartInterval(interTime) {
    runInternalTime = setInterval(run, interTime);
}

exports.StopInterval = function StopInterval() {
    clearInterval(runInternalTime);
}

const doTask = async (task) => {  
    try {    
        const data = await task.func(task.options);
        log.info(`doTask is ${data} fetched for ${task.cnt}`); 
        return data;  
    } catch (error) {    
        log.err(error);  
    }};

async function run() {
    await lk.acquire('run', async () => {
        if (taskList.length <= 0) {
            return;
        }
        var task = taskList[0];
        if (task === undefined) {
            return;
        }
        ret = await doTask(task);
        log.info(`run is ${ret} fetched for ${task.cnt}`); 
        taskList.shift();
    });
}

exports.PushTask = async function(func, options = {}) {
    await lk.acquire('run', async () => {
        if (cnt >= 999999999) {
            cnt = 0;
        }
        cnt += 1;
        var task = {
            cnt: cnt,
            func: func,
            options: options
        }
        taskList.push(task);
        log.info("push task cnt ", cnt);
    });
}